home *** CD-ROM | disk | FTP | other *** search
/ C# & Game Programming - A…er's Guide (2nd Edition) / Buono 2nd Ed.iso / GameClasses / TimedEvent.cs < prev    next >
Text File  |  2004-09-07  |  2KB  |  69 lines

  1. // TimedEvent.cs: A simple class representing a ticking timer
  2. // that can be used in a number of ways. It can be used to
  3. // simply count something that you want to have happen a set
  4. // number of times. Derriving from this class and overriding
  5. // the Tick() method can allow for custom behavior.
  6. using System;
  7.  
  8. namespace GameClasses {
  9.     public delegate void TickHandler(TimedEvent e, Object payload);
  10.  
  11.     public class TimedEvent {
  12.         // Member fields
  13.         public int ticks;
  14.         public int tickCounter;
  15.         public bool isCountdown;
  16.         public bool isActive;
  17.         public TickHandler remoteHandler;
  18.         public object payload;
  19.  
  20.         public TimedEvent() {
  21.             ticks = 0;
  22.             isCountdown = false;
  23.             SetTickHandler(new TickHandler(DoNothing));
  24.         }
  25.  
  26.         public TimedEvent(TickHandler handler) {
  27.             SetTickHandler(handler);
  28.         }
  29.  
  30.         public TimedEvent(int numTicks, TickHandler handler) {
  31.             SetCountdown(numTicks);
  32.             SetTickHandler(handler);
  33.         }
  34.  
  35.         public void SetTickHandler(TickHandler handler) {
  36.             remoteHandler = handler;
  37.         }
  38.  
  39.         public void SetCountdown(int numTicks) {
  40.             isCountdown = numTicks > 0;
  41.             ticks = numTicks;
  42.             tickCounter = ticks;
  43.         }
  44.  
  45.         public void Tick() {
  46.             if (!isActive)
  47.                 return;
  48.  
  49.             // Call any custom function
  50.             remoteHandler(this, payload);
  51.  
  52.             // decrement the counter
  53.             if (isCountdown)
  54.                 if (tickCounter > 0)
  55.                     tickCounter--;
  56.                 else
  57.                     isActive = false;
  58.         }
  59.  
  60.         public void Reset() {
  61.             tickCounter = ticks;
  62.             isActive = true;
  63.         }
  64.  
  65.         // Dummy for default tick-handler
  66.         public void DoNothing(TimedEvent e, Object o) {}
  67.     }
  68. }
  69.